package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.Brand;
import org.dromara.system.domain.ProductsLine;
import org.dromara.system.domain.bo.BrandBo;
import org.dromara.system.domain.vo.BrandVo;
import org.dromara.system.mapper.BrandMapper;
import org.dromara.system.service.IBrandService;
import org.dromara.system.service.IProductsLineService;
import org.dromara.system.service.impl.permission.PermissionBaseService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 品牌Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-14
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {

    private final IProductsLineService productsLineService;
    private final PermissionBaseService permissionBaseService;

    /**
     * 查询品牌
     *
     * @param id 主键
     * @return 品牌
     */
    @Override
    public BrandVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询品牌列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 品牌分页列表
     */
    @Override
    public TableDataInfo<BrandVo> queryPageList(BrandBo bo, PageQuery pageQuery) {
        permissionBaseService.aloneAssignPermission(bo);
        IPage<BrandVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<BrandVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    /**
     * 查询符合条件的品牌列表
     *
     * @param bo 查询条件
     * @return 品牌列表
     */
    @Override
    public List<BrandVo> queryList(BrandBo bo) {
        LambdaQueryWrapper<Brand> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Brand> buildQueryWrapper(BrandBo bo) {
        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(Brand::getId);
        lqw.eq(bo.getUserId() != null, Brand::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), Brand::getCode, bo.getCode());

        return lqw;
    }

    /**
     * 新增品牌
     *
     * @param bo 品牌
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BrandBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())){
            bo.setUserId(LoginHelper.getUserId());
        }
        Brand add = MapstructUtils.convert(bo, Brand.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改品牌
     *
     * @param bo 品牌
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BrandBo bo) {
        Brand update = MapstructUtils.convert(bo, Brand.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Brand entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除品牌信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            List<ProductsLine> productsLines = productsLineService.lambdaQuery().in(ProductsLine::getBrandId, ids).list();
            BusinessException.isTrue(CollUtil.isNotEmpty(productsLines), "品牌上存在产品线，禁止删除品牌！");
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

}
